﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pro.DataServiceInterface;
using Pro.Models;

namespace Pro.DataAccess
{
    public abstract class BaseService<T> : IBaseService<T>
        where T : BaseModel
    {
        private class Entities : ProDbContext
        {
            public DbSet<T> EntitySet { get; set; }
        }
        private readonly Entities _db = new Entities();

        public virtual T Get(int id)
        {
            return _db.EntitySet.Find(id);
        }

        public virtual T Add(T model)
        {
            var result = _db.EntitySet.Add(model);
            _db.Commit();
            return result;
        }

        public virtual void Update(T model)
        {
            _db.EntitySet.AddOrUpdate(model);
            _db.Commit();
        }

        public virtual void Delete(T model)
        {
            model.Deleted = true;
            Update(model);
        }


        public virtual void Restore(T model)
        {
            model.Deleted = false;
            Update(model);
        }

        public virtual T ShiftDelete(T model)
        {
            var result = _db.EntitySet.Remove(model);
            _db.Commit();
            return result;
        }

        public virtual IQueryable<T> GetQueryable()
        {
            return _db.EntitySet;
        }

        public virtual IEnumerable<T> AddRange(IEnumerable<T> list)
        {
            var result = _db.EntitySet.AddRange(list);
            _db.Commit();
            return result;
        }

        public virtual void Initialize()
        {
        }

        public virtual void Commit()
        {
            _db.SaveChanges();
        }
    }
}
